package net.dodo.robot;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Robot;

/**
 * 
 * @author yanping
 * 
 */
public class ZmrRobot extends Robot implements IRobot {

	public ZmrRobot() throws AWTException {
		super();
	}

	/**
	 * 鼠标点击事件
	 * 
	 * @param robot
	 *            robot实例
	 * @param buttons
	 *            点击鼠标的类型(左键右键)
	 * @param times
	 *            点击鼠标次数
	 * @param delay
	 *            如果点击不止一次(中间的延迟时间)
	 */
	@Override
	public void click(Robot robot, int buttons, int times, int delay) {
		for (int i = 0; i < times; i++) {
			robot.mousePress(buttons);
			if (0 < delay) {
				robot.delay(delay);
				robot.mouseRelease(buttons);
			}
		}
	}

	/**
	 * 鼠标点击事件
	 * 
	 * @param robot
	 *            robot实例
	 * @param button
	 *            点击鼠标的类型(左键右键)
	 * @param times
	 *            点击鼠标次数
	 * @param delay
	 *            如果点击不止一次(中间的延迟时间)
	 */
	@Override
	public void doubleClick(Robot robot, int button, int delay) {
		for (int i = 0; i < 2; i++) {
			robot.mousePress(button);
			if (0 < delay) {
				robot.delay(delay);
				robot.mouseRelease(button);
				robot.mousePress(button);
				robot.mouseRelease(button);
			}
		}
	}

	/**
	 * 是否进入房间
	 * 
	 * @param robot
	 * @return
	 */
	public synchronized boolean enteredRoom(Robot robot, int x, int y, int ix,
			int iy) {
		boolean isEntered = false;
		// 输入框的xy值
		int localx = x, localy = y;
		robot.mouseMove(x, y);
		doubleClick(robot, 1, 200);
		// 鼠标移动到输入框位置
		robot.mouseMove(ix, iy);
		// 获取屏幕颜色
		Color c = robot.getPixelColor(x, y);
		float r = c.getRed(), g = c.getGreen(), b = c.getBlue();
		// 这里判断逻辑(屏幕颜色是否为白色,定位到平台输入框)
		if (r == g && g == b) {
			System.out.println("r=" + r + "\tg=" + g + "\tb=" + b);
			isEntered = r == 125f ? true : false;
		}
		if (!isEntered) {
			try {
				// 测试时候可以移动鼠标来kill掉当前的进程
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return enteredRoom(robot, localx, localy, ix, iy);
		}
		return isEntered;
	}
}
